<template>
  <div class="map-content">
    <div ref="mapChart" style="width: 100%; height: 50vh"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import fujianJSON from '@/assets/json/fujian.json'
import sanmingJson from '@/assets/json/sanming.json'
import nanpingJson from '@/assets/json/nanping.json'
import ningdeJson from '@/assets/json/ningde.json'
import fuzhouJson from '@/assets/json/fuzhou.json'
import putianJson from '@/assets/json/putian.json'
import quanzhouJson from '@/assets/json/quanzhou.json'
import xiamenJson from '@/assets/json/xiamen.json'
import zhangzhouJson from '@/assets/json/zhangzhou.json'
import longyanJson from '@/assets/json/longyan.json'
import * as echarts from 'echarts'
import { watch } from 'vue'

// ref or data
const mapChart = ref()
let options = {}
let myMapChart: any = null
const zoom = 0.7
let dt: any = [
  {
    name: '南平市',
    unitId: '10350701'
  },
  {
    name: '宁德市',
    unitId: '10350901'
  },
  {
    name: '三明市',
    unitId: '10350401'
  },
  {
    name: '福州市',
    unitId: '10350101'
  },
  {
    name: '莆田市',
    unitId: '10350301'
  },
  {
    name: '泉州市',
    unitId: '10350501'
  },
  {
    name: '龙岩市',
    unitId: '10350801'
  },
  {
    name: '漳州市',
    unitId: '10350601'
  },
  {
    name: '厦门市',
    unitId: '10350201'
  }
]

// 标记点数据
//鼠标事件;
let activeAreaName = ''

// 引导线标记点数据坐标+偏移量
const COORDS_LINE: any = {
  武夷烟叶: [
    [117.495646, 27.294385],
    [115.2, 26.94]
  ],
  福建进出口: [
    [118.104901, 24.473043],
    [120.104, 24.86]
  ],
  三明金叶复烤: [
    [117.555184, 26.179113],
    [115.1, 26.18]
  ],
  海晟投资: [
    [118.112537, 24.477882],
    [120.26, 25.48]
  ]
}

const pieces = [
  {
    min: 630,
    label: '好(630分以上)',
    color: '#70ad47',
    richKey: 'c1'
  },
  {
    min: 420,
    max: 559,
    label: '一般(420分~559分)',
    color: '#f7c679',
    richKey: 'c2'
  },
  {
    min: 560,
    max: 629.99,
    label: '较好(560分~629.99分)',
    color: '#ffdaa6',
    richKey: 'c3'
  },
  {
    max: 420,
    label: '差(420分以下)',
    color: '#ff7875',
    richKey: 'c4'
  }
]

// map 各区 分数
let _data_: any = [
  {
    // name: 'XXX1',
    name: '武夷烟叶',
    unitId: '14350701'
  },
  {
    name: '福建进出口',
    unitId: '18350001'
  },
  {
    name: '三明金叶复烤',
    unitId: '23500400'
  },
  {
    name: '海晟投资',
    unitId: '43501200'
  }
]

// emits
const emits = defineEmits({
  CMapChartClick: (data) => !!data,
  setMapUnitId: (data) => !!data
})

const props = defineProps({
  allAreaData: {
    type: Object,
    default: () => {}
  }
})

watch(
  () => props.allAreaData,
  (newVal: any) => {
    // 县市
    if (newVal && newVal.area && newVal.area.length) {
      newVal.area.forEach((item: any) => {
        dt.forEach((v: any) => {
          if (Number(v.unitId) === Number(item.unitId)) v.value = item.score
        })
      })
    }
    if (newVal && newVal.unit && newVal.unit.length) {
      newVal.unit.forEach((item: any) => {
        _data_.forEach((v: any) => {
          if (Number(v.unitId) === Number(item.unitId))
            v.value = Number(item.score)
        })
      })
    }

    nextTick(() => {
      initOptions()
    })
  },
  {
    deep: true
  }
)

onMounted(() => {
  // if (mTime.value) clearInterval(mTime.value)
  // initOptions()
})

function determineGroupObject(score: number, pieces: any[] = []) {
  for (const piece of pieces) {
    if (piece.min !== undefined && piece.max !== undefined) {
      if (score >= Number(piece.min) && score <= Number(piece.max)) {
        return piece
      }
    } else if (piece.min !== undefined) {
      if (score >= Number(piece.min)) {
        return piece
      }
    } else if (piece.max !== undefined) {
      if (score <= Number(piece.max)) {
        return piece
      }
    }
  }
  return undefined
}

function genLabelRich() {
  const rich: Record<string, any> = {}
  pieces.forEach((p) => {
    rich[p.richKey] = {
      align: 'center',
      lineHeight: 17,
      fontSize: 14,
      color: '#fff',
      backgroundColor: p.color,
      width: 100,
      height: 25,
      borderRadius: [4, 4, 0, 0]
    }
  })

  return rich
}

// mwthod
const initOptions = () => {
  echarts.registerMap('fujianJSON', fujianJSON as any)
  myMapChart = echarts.init(mapChart.value)

  // 判断 地图显示那个颜色的数据源
  options = {
    series: [
      {
        type: 'map',
        map: 'fujianJSON',
        zlevel: 0,
        zoom: zoom,
        // 地图是否开启鼠标滚动缩放或拖拽
        // roam: true,
        // silent: true, //禁用地图的hover事件
        itemStyle: {
          normal: {
            // borderColor: 'transparent',
            color: '#333',
            // 地图默认背景颜色
            areaColor: '#409eff',
            borderColor: '#fff',
            borderWidth: 0.2
          },
          // 鼠标移动地图时的背景颜色
          emphasis: {
            areaColor: '#4B7902',
            label: {
              show: true,
              textStyle: {
                color: '#fff' //鼠标经过字体颜色
              }
            }
          }
        },
        label: {
          normal: {
            show: true,
            textStyle: {
              color: '#333'
            }
          }
        },
        layoutCenter: ['45%', '50%'],
        layoutSize: '120%',
        data: dt,
        selectedMode: false // 去除地图点击后的黄色背景颜色
      },
      {
        type: 'lines',
        z: 3,
        coordinateSystem: 'geo',
        symbol:
          'image://',
        symbolSize: [10, 0], //只保留地图端标记
        opacity: 1,
        label: {
          show: true,
          position: 'end',
          formatter: function (params: any) {
            //文本提示框 '}\n{value| 分数:' + params.value +

            const piece = determineGroupObject(params.value, pieces)

            return `{${piece?.richKey || 'title'}|  ${params.name} }`
            // return
          },
          backgroundColor: '#7ec4ff',
          borderColor: '#fff',
          borderWidth: 1,
          borderRadius: 4,
          align: 'center',
          width: 100,
          rich: {
            //标题样式
            title: {
              align: 'center',
              lineHeight: 17,
              fontSize: 14,
              color: '#fff',
              backgroundColor: '#34A0FF',
              width: 100,
              height: 25,
              borderRadius: [4, 4, 0, 0]
            },
            ...genLabelRich(),
            value: {
              //内容样式
              height: 25,
              width: 100,
              color: '#34A0FF',
              backgroundColor: '#fff',
              borderRadius: [0, 0, 4, 4]
            }
          }
        },
        lineStyle: {
          //视觉引导线属性
          type: 'dashed',
          opacity: 1,
          color: '#70b7ff', //引导线颜色
          curveness: 0.1
        },
        data: _data_.map((item: any) => {
          let label = {}
          if (item.name === activeAreaName) {
            label = {
              //
              // '}\n{value| 分数:' +
              //     params.value +
              formatter: function (params: any) {
                return '{title|' + params.name + '}'
              },
              backgroundColor: '#FFB569',
              borderColor: '#FFB569',
              width: 100,
              rich: {
                title_active: {
                  align: 'center',
                  lineHeight: 17,
                  fontSize: 12,
                  color: '#fff',
                  backgroundColor: '#FFB569',
                  width: 100,
                  height: 25,
                  borderRadius: [4, 4, 0, 0]
                },
                value_active: {
                  height: 25,
                  width: 100,
                  color: '#FFB569',
                  backgroundColor: '#fff',
                  borderRadius: [0, 0, 4, 4]
                }
              }
            }
          }
          return Object.assign(
            {
              coords: COORDS_LINE[item.name],
              label
            },
            item
          )
        })
      }
    ],
    visualMap: {
      //视觉映射组件
      type: 'piecewise', //分段型。
      splitNumber: 6,
      inverse: true,
      pieces,
      seriesIndex: 0,
      left: 'right',
      bottom: '0%',
      textStyle: {
        color: '#333'
      }
    },
    geo: {
      map: 'fujianJSON',
      // 地图缩放
      zoom: zoom,
      // roam: true,
      layoutCenter: ['45%', '50%'],
      layoutSize: '120%',
      itemStyle: {
        normal: {
          borderColor: '#c0f3fb',
          borderWidth: 1,
          shadowColor: '#8cd3ef',
          shadowOffsetY: 10,
          shadowBlur: 100,
          //  地图阴影颜色
          areaColor: 'transparent'
        }
      }
    }
  }

  if (options && typeof options === 'object') {
    myMapChart.setOption(options)
  }
  // 地图点击事件
  myMapChart.on('click', (e: any) => {
    // console.log(e, 'e---')
    if (
      e.name === '武夷烟叶' ||
      e.name === '三明金叶复烤' ||
      e.name === '海晟投资' ||
      e.name === '福建进出口'
    )
      return
    let newMapJson = {}
    // 最笨的方法
    if (e.name === '三明市') newMapJson = sanmingJson
    else if (e.name === '南平市') newMapJson = nanpingJson
    else if (e.name === '宁德市') newMapJson = ningdeJson
    else if (e.name === '福州市') newMapJson = fuzhouJson
    else if (e.name === '莆田市') newMapJson = putianJson
    else if (e.name === '泉州市') newMapJson = quanzhouJson
    else if (e.name === '厦门市') newMapJson = xiamenJson
    else if (e.name === '漳州市') newMapJson = zhangzhouJson
    else newMapJson = longyanJson
    const data = {
      showCMap: false,
      mapData: e.data,
      newMapData: newMapJson
    }
    emits('CMapChartClick', data)
    emits('setMapUnitId', e.data?.unitId)
  })

  window.addEventListener('resize', resize)
}

const resize = () => {
  setTimeout(() => {
    if (myMapChart) {
      myMapChart.resize()
    }
  }, 50)
}

defineOptions({
  name: 'CMap'
})
</script>

<style scoped lang="scss">
.map-content {
  display: flex;
  align-items: flex-end;
  .moddle_box {
    width: 200px;
    .middle-div {
      display: flex;
      align-items: center;
      padding-top: 4px;
      padding-bottom: 4px;
      font-size: 12px;
      .middle-span {
        width: 10px;
        height: 10px;
        margin-right: 10px;
      }
      .item1 {
        background-color: #85b962;
      }

      .item2 {
        background-color: #ffff26;
      }

      .item3 {
        background-color: #ffc926;
      }

      .item4 {
        background-color: #ff2626;
      }
    }
  }
}
</style>
